<template>
  <div>
    <el-dialog
      :visible="showEditDialog"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :show-close="true"
      class="medium-common-dialog-size"
      @closed="handleClose"
    >
      <el-form ref="contactRef" :rules="rules" :model="formData" :class="{'mobile-el-form': showMobilePage}" :label-position="showMobilePage?'left':'right'" label-width="96px">
        <Title :title="isEdit ? '编辑联系人' : '新建联系人'" style="margin-bottom:12px" font-size="16px"/>
        <el-row type="flex" class="response-el-row">
          <el-col :span="12" >
            <el-form-item label="客户联系人" prop="contactPerson">
              <el-input
                v-model.trim="formData.contactPerson"
                :maxlength="50"
                :disabled="isEdit"
                size="small"
                name="contactPerson"
                placeholder="请输入客户联系人"
                type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="联系方式" prop="tel">
              <el-input
                v-model.trim="formData.tel"
                :maxlength="50"
                size="small"
                name="tel"
                placeholder="请输入联系方式"
                type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="协作人">
              <selectWithUserLoad
                ref="proposerRef"
                v-model="formData.associate"
                :hide-select-list="formData.associate || []"
                :value-type="'object'"
                :show-check-user="true"
                placeholder="请选择人员"
                key-name="id"
                label-name="userName"
                filterable
                multiple
                collapse-tags
                clearable
                @change="setCoDepartment"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="协作部门">
              <ToolTip :content="formatName(formData.coDepartment)"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="状态">
              <el-switch
                v-model="formData.status"
                :active-value="1"
                :inactive-value="0"
                active-color="#406EFF"
                inactive-color="#cccccc"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="备注" class="remark">
              <el-input v-model.trim="formData.remark" :maxlength="200" size="small" class="client-textarea" name="remark" type="text" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="flex-center btns">
        <el-button class="ok submit-btn" type="primary" size="small" @click="handleSubmit">确定<i v-if="submitLoading" class="el-icon-loading"/></el-button>
        <el-button class="back-btn cancel-btn-style" size="small" @click="handleClose">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import Title from '@/components/Title';
import { editContact, addClientContact } from '@/api/customer';
import ElMessage from '@/utils/message';
import { arrRepeat, formatName } from '@/utils/tools';
import { mapState } from 'vuex';

export default {
  components: { Title, selectWithUserLoad },
  props: {
    customerId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      showEditDialog: false,
      groupList: [],
      rules: {
        contactPerson: [{ required: true, trigger: 'blur', message: '请输入客户联系人' }],
        tel: [{ required: true, trigger: 'blur', message: '请输入联系方式' }]
      },
      isEdit: false,
      submitLoading: false,
      formData: {
        contactPerson: '',
        coDepartment: [],
        status: 1
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage,
      'userInfo': state => state.user.userInfo
    })
  },
  methods: {
    arrRepeat,
    formatName,
    setCoDepartment(val) {
      if (val && val.length) {
        // 拼接用户的子级部门，还要去重
        let temp = [];
        val.forEach(item => {
          temp = temp.concat(item.currentDepartment);
        });
        const res = this.arrRepeat(temp);
        this.formData.coDepartment = res;
      } else {
        this.formData.coDepartment = [];
      }
    },
    openDialog(data) {
      if (data) {
        this.isEdit = true;
        this.formData = JSON.parse(JSON.stringify(data));
      }
      this.showEditDialog = true;
    },
    handleSubmit: _.debounce(function() {
      this.$refs.contactRef.validate((valid) => {
        if (valid) {
          this.toSubmit();
        } else {
          return false;
        }
      });
    }, 500),
    async toSubmit() {
      const params = JSON.parse(JSON.stringify(this.formData));
      if (params.associate) {
        let temp = [];
        params.associate = params.associate.map(item => {
          if (item.currentDepartment) {
            temp = temp.concat(item.currentDepartment);
          }
          return item.id;
        });
        params.coDepartment = temp.map(item => item.id);
      }
      try {
        let res;
        if (this.isEdit) {
          res = await editContact(params.id, params);
        } else {
          res = await addClientContact(this.customerId, params);
        }
        if (res.code === 200) {
          ElMessage.success('操作成功');
          this.$emit('updateDetail');
          this.handleClose();
        }
      } catch (err) {
        console.log(err);
      }
    },
    handleClose() {
      this.formData = {};
      this.isEdit = false;
      this.$refs.contactRef.resetFields();
      this.showEditDialog = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.btns {
  justify-content: center;
}
</style>
